package cn.com.basic.framework.web.domain;

import cn.com.basic.framework.exception.enums.IErrorCode;
import cn.com.basic.framework.exception.enums.errors.CommonCode;
import cn.com.basic.framework.exception.exceptions.SysException;
import cn.com.basic.framework.web.error.BizException;
import cn.hutool.core.lang.Validator;
import cn.hutool.json.JSONUtil;
import lombok.Builder;
import lombok.Data;

/**
 * 响应结果
 *
 * @author shaodl
 */
@Data
@Builder
public class RespResult<T> {

    /**
     * 状态码 非异常 200
     */
    private String code;
    /**
     * 状态值 非异常 success
     */
    private String message;
    /**
     * 返回值
     */
    private T data;

    public RespResult(String code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    private RespResult() {
    }

    private RespResult(T data) {
        this.code = CommonCode.SUCCESS_STATUS.getKey();
        this.message = CommonCode.SUCCESS_STATUS.getValue();
        this.data = data;
    }

    private RespResult(IErrorCode error, String message, T data) {
        this.code = error.getKey();
        this.message = error.getValue();
        if (Validator.isNotEmpty(message)) {
            this.message = message;
        }
        this.data = data;
    }

    private RespResult(SysException e, T data) {
        this.code = e.getError().getKey();
        this.message = e.getError().getValue();
        this.data = data;
    }

    private RespResult(BizException e, String message) {
        this.code = e.getErrorCode();
        this.message = message;
        this.data = null;
    }

    public static RespResult success(Object data) {
        return new RespResult(data);
    }

    public static RespResult success(String message) {
        return new RespResult(CommonCode.SUCCESS_STATUS, message, null);
    }


    public static RespResult success() {
        return new RespResult(null);
    }


    public static RespResult error(SysException e) {
        return error(e, null);
    }

    public static RespResult error(SysException e, Object data) {
        return new RespResult(e, data);
    }

    public static RespResult error(IErrorCode error) {
        return error(error, null);
    }

    public static RespResult error(IErrorCode error, Object data) {
        return new RespResult(error, error.getValue(), data);
    }

    public static RespResult error(IErrorCode error, String message) {
        return new RespResult(error, message, null);
    }

    public static RespResult error(BizException bizException) {
        return new RespResult(bizException);
    }

    @Override
    public String toString() {
        return JSONUtil.toJsonPrettyStr(this);
    }
}
